from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import CreateAPIView, GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from areas.utils import merge_cart_cookie_to_redis
from oauth.serializers import OAuthUserSerializer
from meiduo_mall.utils.exceptions import logger
from oauth.exceptions import QQAPIError
from oauth.models import OAuthQQUser
from oauth.utils import OAuthQQ


# 前端页面点击qq登录调用这个视图
class QQAuthURLView(APIView):
    """
    QQ登陆url地址
    """

    def get(self, request):
        next = request.query_params.get('next', '/')
        # 获取qq登录url地址
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_login_url()
        return Response({
            'login_url': login_url
        })


# QQ手机扫码确认登录回调和绑定用户用这个视图
class QQAuthUserView(CreateAPIView):
    serializer_class = OAuthUserSerializer

# 数据绑定调用
#     def post(self, request):
#         """
#         保存绑定QQ登录用户的数据:
#         1. 获取参数并进行校验(参数完整性，手机号格式，access_token是否有效，短信验证码是否正确)
#         2. 保存绑定QQ登录用户的数据并签发jwt token
#         3. 返回响应数据
#         """
#         # 1. 获取参数并进行校验(参数完整性，手机号格式，access_token是否有效，短信验证码是否正确)
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#
#         # 2. 保存绑定QQ登录用户的数据并签发jwt token (create)
#         serializer.save()
#         # 3. 返回响应数据
#         return Response(serializer.data, status=status.HTTP_201_CREATED)


# QQ扫码确定调用函数
    def get(self, request):
        # 获取qq返回的code

        code = request.query_params.get('code')
        try:
            # 根据code获取access_token
            oauth = OAuthQQ()
            access_token = oauth.get_access_token(code)
            # 根据access_token 获取授权QQ用户的openid
            openid = oauth.get_openid(access_token)
        except QQAPIError as e:
            logger.error(e)
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # 根据`openid`查询tb_oatu_qq表，判断是否已经绑定账号
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            # 如果没有绑定，则返回token
            token = oauth.generate_save_user_token(openid)
            return Response({'access_token': token})
        else:
            # 4.1 如果已经绑定，生成JWT token信息
            # 补充生成记录登录状态的token
            user = oauth_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            # 合并购物车
            response = merge_cart_cookie_to_redis(request, user, response)
            return response

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)

        # 合并购物车
        response = merge_cart_cookie_to_redis(request, self.user, response)
        return response
